// 封装一个简易的埋点服务

import { Button as SDButton } from "@/components/ui"
import { useEffect } from "react"


const trackService = {
    sendEvent: <T,>(trackType: string, data?: T) => {
        const trackData = {
            timestamp: new Date().toISOString(), // 时间戳
            trackType, // 跟踪事件类型
            data, // 事件数据
            userAgent: navigator.userAgent, // 用户代理
            url: window.location.href // 当前页面 URL
        }

        // navigator.sendBeacon() 方法可用于通过 HTTP POST 将少量数据 异步 传输到 Web 服务器
        // https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/sendBeacon
        navigator.sendBeacon('https://example.com/api/track', JSON.stringify(trackData))
    }
}

// 二次封装组件
const widthTrack = (Component: React.ComponentType<any>, trackType: string) => {
    return (props: any) => {
        useEffect(() => {
            trackService.sendEvent(`${trackType}-Mount`)
            return () => {
                trackService.sendEvent(`${trackType}-UnMount`)
            }
        }, [])

        const trackEvent = (eventType: string, eventData?: any) => {
            trackService.sendEvent(`${trackType}-${eventType}`, eventData)
        }

        return <Component {...props} trackEvent={trackEvent} />
    }

}

const Button = ({ trackEvent }: { trackEvent: (eventType: string, eventData?: any) => void }) => {
    const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
        trackEvent(e.type, {
            name: e.type,
            type: e.type,
            x: e.clientX,
            y: e.clientY,
        })
    }
    return <SDButton onClick={handleClick}>埋点</SDButton>
}

export const TrackButton = widthTrack(Button, 'button')

